<?php

namespace app\common\service;
use think\cache\driver;


class RedisQuantity
{
    const LIMIT = 1;

    /**
     * redis 频率控制
     * @param $lockKeyName 限制的名称
     * @param $timeout  限制的秒数
     * @param int $amountLimit
     * @return bool
     */
    public static function FrequencyLimit($lockKeyName, $timeout, $amountLimit = 1)
    {
        $redis = new driver\Redis();
        $lockKeyName = 'lock' . $lockKeyName.request()->ip();
        $lockKeyName=md5($lockKeyName);
        /* 防止死锁 */
        if ($redis->ttl($lockKeyName) == -1) {
            $redis->del($lockKeyName);
        }
//		判断是否有该值 没有则添加频率控制和过期时间
        if (!$redis->has($lockKeyName)) {
            $redis->setnx($lockKeyName, self::LIMIT);
            $redis->expire($lockKeyName, $timeout);
        } else {
            if ($redis->inc($lockKeyName, self::LIMIT) > $amountLimit) return false;
        }
        return true;
    }

    /**
     * 释放频率限制
     * @param $lockKeyName
     * @return bool
     */
    public static function unFrequencyLimit($lockKeyName)
    {
        $redis =  new driver\Redis();
        $lockKeyName = 'lock_submit' . $lockKeyName;
        return $redis->del($lockKeyName);
    }
}